package com.huadragon.marathoncore.util;





import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.jdbc.support.nativejdbc.OracleJdbc4NativeJdbcExtractor;

import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xuyulong on 2016.03.28
 */
public final class JsonUtil {
	private final static ExtandObjectMapper mapper = new ExtandObjectMapper();
    private static ObjectMapper objectMapper = null;

    static {
        objectMapper = new ObjectMapper();
//        自动的忽略掉不存在的字段的转换
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    /*
    * 序列化.
    * */
    public static String toJson(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (Exception e) {
            return "";
        }
    }

    /*
    * json转为对应类.
    *
    * */
    public static <T> T json2pojo(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr, clazz);
        } catch (IOException e) {
            return null;
        }
    }

    /*
    * json转为对应集合类.
    * */
    public static <T> Map<String, Object> json2map(String jsonStr) {
        try {
            return objectMapper.readValue(jsonStr, Map.class);
        } catch (IOException e) {
            return null;
        }
    }
    /*
    * 集合转目标对象.
    * */
    public static <T> T map2pojo(Map map, Class<T> clazz) {
        return objectMapper.convertValue(map, clazz);
    }
    
    /** 
     * 将对象转换为json字符串 
     *  
     * @param obj 
     * @return 
     * @throws Exception 
     */  
    public static String obj2string(Object obj) {  
    	if (obj==null) {
			return "";
		}
        StringWriter sw = new StringWriter();  
        try {  
        	mapper.writeValue(sw, obj);  
        } catch (Exception e) { 
        	throw new RuntimeException("序列化时出错:"+e.getMessage());
        }  
        return sw.toString();  
    }   
  
    /** 
     * 将字符串转为对象 
     *  
     * @param <T> 
     * @param jsonStr 
     * @param cls 
     * @return 
     */  
    public static <T> T str2obj(String jsonStr, Class<T> cls) {  
        T obj = null;  
        try {  
            obj = mapper.readValue(jsonStr, cls);  
        } catch (Exception e) {  
        	throw new RuntimeException("反序列化时出错："+e.getMessage());
        }  
        return obj;  
    }  

}
